<template>
  <div class="container">
    <div class="title">
      <div class="icon"></div>
      <div class="text">{{ stationName }}</div>
    </div>
    <van-field
      v-model="amt"
      placeholder="消费金额"
      input-align="right"
      extra-event-params
      @focus="prevent"
      label="￥"
    />
    <van-number-keyboard
      :show="isShow"
      v-model="amt"
      theme="custom"
      extra-key="."
      close-button-text="确认支付"
      @blur="isShow = false"
      @close="checkPassword"
    />
  </div>
</template>
<script>
// 借用闪付的授权逻辑
import settings from "@/settings";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import UrlFactory from "@/utils/urlFactory";
import Vue from "vue";
import { Field, NumberKeyboard, Toast } from "vant";
Vue.use(Field);
Vue.use(NumberKeyboard);
import { getAuthenSK } from "@/utils/getAuthenSK";

export default {
  data() {
    return {
      amt: null,
      isShow: true,
      // enterpriseId: this.$store.state.authen.enterpriseId,
      stationName: this.$store.state.getSK.stationId,
      stationId: this.$store.state.getSK.stationName
    };
  },
  computed: {
    ...mapGetters({
      openId: "authen/openId",
      enterpriseId: "authen/enterpriseId"
    })
  },
  async created() {
    if(!this.openId){
      getAuthenSK()
     return
    }

    //  // openid 认证 回来 -> 开始手机认证
    //   const openIdRes = await this.queryOpenIdByEnterpriseId(this.enterpriseId);
    //   const openId1 = openIdRes.openId;
    //   console.log("闪付授权中间页--存了openId" + openId);
    //   this.$store.commit("authen/setEnterpriseId", enterpriseId);
    //   this.$store.commit("authen/setOpenId", openId1);

    //   console.log("再走一遍授权--有openId了", extStr);
    //   getAuthenSK(extStr, "remit");




      let state = this.$route.query.state; // 0
      let outerStr = this.$route.query.outer_str; // 1
      let openId = this.$route.query.openid; // 1 2 3   
      let originUrl = this.$route.query.originurl; // 3
      // let enterpriseId = "";
      let extStr = "";
       if (!!state) {
        extStr = state;
      }
      const urlInfo = this.parseExtStr(extStr);
      
  },
  watch: {
    amt() {
      this.updateChangeAmount(this.amt);
    }
  },
  methods: {
    //解析地址
     parseExtStr(extStr) {
      let searchObj;
      let searchStr;
      let enterpriseId;

      const [url, str] = extStr.split(".");
      if (str !== undefined) {
        searchStr = str.replace(/-/g, "&").replace(/_/g, "=");
        searchObj = querystring.parse(searchStr);
      } else {
        searchStr = "";
        searchObj = {};
      }

      let enterpriseIdArr = url.replace(/\//, "").match(/^\d{1,}/);
      if (enterpriseIdArr == null) {
        enterpriseId = "";
      } else {
        enterpriseId = enterpriseIdArr[0];
      }

      return {
        fullUrl: url + (searchStr != "" ? "?" : "") + searchStr,
        firstUrl: url,
        searchObj,
        enterpriseId
      };
    },
    // 阻止手机输入框
    prevent() {
      document.activeElement.blur();
      this.isShow = true;
    },
    // 获取openId
    async queryOpenIdByEnterpriseId(enterpriseId) {
      const code = this.$route.query.code;
      const gzhAuthenRes = await this.$axios.$get("/getGzhAuthorizeInfo", {
        params: {
          code,
          enterpriseId: enterpriseId
        }
      });
      if (gzhAuthenRes.retCode !== 0) {
        return Promise.reject("拉取openId失败");
      }
      const openId = gzhAuthenRes.data.openid;
      console.log("拉取的openId为", openId);
      return Promise.resolve({
        enterpriseId,
        openId
      });
    },
    // 修改充值金额
    updateChangeAmount(value) {
      this.amt = value
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".")
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      // if (price.indexOf(".") < 0 && price != "") {
      //   // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      //   this.chargeAmount = '';
      // }
      // console.log('函数' + this.chargeAmount);
    },
    // 截取url参数
    getUrlParams(url) {
      let urlStr = url.split("?")[1];
      const urlSearchParams = new URLSearchParams(urlStr);
      const result = Object.fromEntries(urlSearchParams.entries());
      return result;
    },

    // 确认支付
    checkPassword() {
      this.amt = this.amt.toString().replace(/\.$/g, "");
      if (this.amt <= 0) return new Error("请输入金额");
      this.pay();
      this.isShow = false;
    },
    async pay() {
      try {
        // 创建订单
        const orderData = await this.$axios.$post(
          "/createOrderNotContainActivity",
          {
            receivableAmt: this.amt,
            enterpriseId: this.enterpriseId,
            aliUserId: "1",
            appType: "1",
            cardFlag: "1",
            // gunName: this.oilGunNum,
            // mobilePhone: phone,
            newCreatefalg: "1",
            openId: this.openId,
            orderOriginType: "2",
            payType: "wx",
            // receivableAmt: this.priceValue,
            stationId: this.stationId,
            version: "1.0"
            // userId: this.userId,
            // orderRandomId: this.orderRandomId
          }
        );

        if (orderData.retCode !== 0) {
          throw new Error(orderData.message);
        }

        const orderNo = orderData.data.orderNo;
        console.log(orderNo, "orderNo"); // 拿到订单号
        // 调第三方支付
        const payInfoData = await this.$axios.$post(
          "/toThirdPaymentNotContainActivity",
          {
            amt: this.amt,
            openId: this.openId,
            enterpriseId: this.enterpriseId,
            userType: "1",
            ordNo: orderNo,
            stationId: this.stationId,
            payType: "wx"
            //  this.selectedStation.stationId
            //     ? this.selectedStation.stationId
            //     : this.selectedStation.stationId2
          }
        );
        console.log("payInfoData", payInfoData);
        if (payInfoData.retCode !== 0) {
          throw new Error(payInfoData.message);
        }
        //
        if (payInfoData.data.thirdPayment === "5") {
          window.location.href = payInfoData.data.redirectUrl;
        } else {
          // 微信授权
          const that = this;
          WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            {
              appId: payInfoData.data.payAppId,
              timeStamp: payInfoData.data.payTimeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: payInfoData.data.paynonceStr, // 支付签名随机串，不长于 32
              package: payInfoData.data.payPackage, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: payInfoData.data.paySignType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: payInfoData.data.paySign // 支付签名
            },
            function(res) {
              if (res.err_msg === "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                Toast("支付成功");
              } else {
                Toast("支付失败，请重试");
              }
            }
          );
        }
      } catch (err) {
        alert(err);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  box-sizing: border-box;
  min-height: 100vh;
  background-color: #f5f6f7;
  padding: 0.2rem;
  .title {
    display: flex;
    align-items: center;
    .icon {
      background: url("../../../static/fuel/jiayouzhan.png") no-repeat;
      width: 1.5rem;
      height: 1.5rem;
      background-size: 100% 100%;
      margin: 0.2rem;
      border-radius: 50%;
    }
    .text {
      font-size: 20px;
      //   height: 1.5rem;
      //   line-height: 1.5rem;
      word-break: break-all;
      flex: 1;
    }
  }
  ::-webkit-input-placeholder {
    text-align-last: left;
  }
  .label-focus {
    font-size: 12px;
    transform: translate3d(0, -12px, 0);
  }

  .label-blur {
    font-size: 16px;
    transform: translate3d(0, 0, 0);
  }
}

.van-cell {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  box-sizing: border-box;
  width: 100%;
  padding: 20px 16px;
  overflow: hidden;
  color: #323233;
  font-size: 20px;
  line-height: 30px;
  background-color: #fff;
}
</style>
